package com.eportal.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 工具类
 */
public class Tools {
    //创建日期格式
    private static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    private static SimpleDateFormat df_ = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private static Logger log = Logger.getLogger(Tools.class);
    /**
     * 取得指定图片的宽度与高度
     */
    public static Map getPicWidthHeight(String filename) {
        Map map = new HashMap();
        try {
            BufferedImage sourceImg = javax.imageio.ImageIO.read(new FileInputStream(filename));
            map.put("width", sourceImg.getWidth());
            map.put("height", sourceImg.getHeight());
            return map;
        } catch (Exception e) {
        	log.error("error",e);
            return null;
        }
    }


    /**
     * 取得随机主文件名
     */
    public synchronized static String getRndFilename() {
        return String.valueOf(System.currentTimeMillis());
    }

    /**
     * 取得指定文件的文件扩展名
     */
    public synchronized static String getFileExtName(String filename) {
        int p = filename.indexOf(".");
        return filename.substring(p);
    }

    /**
     * 验证上传文件的类型是否合法 fileType:1-图片 2-视频
     */
    public synchronized static boolean isEnableUploadType(int fileType, String filename) {
        String enableExtNames = null;
        int p = filename.indexOf(".");
        String fileExtName = filename.substring(p).toLowerCase();
        if (fileType == 1) {//图片文件类型
            enableExtNames = ".jpg,.gif,.png";
        } else if (fileType == 2) {//视频文件类型
            enableExtNames = ".flv";
        }
        if (enableExtNames != null) {
            return enableExtNames.indexOf(fileExtName) != -1;
        } else {
            return true;
        }

    }

    /**
     * HTML代码的Escape处理方法,原来的算法是escapeb，因为在php那边不好处理所以先去掉
     */
    public static String escape(String src) {
        return src;
    }

    /**
     * HTML代码的UnEscape处理方法,原来的算法是unescapeb，因为在php那边不好处理所以先去掉
     */
    public static String unescape(String src) {
        return src;
    }

    /**
     * HTML代码的Escape处理方法
     */
    public static String escapeb(String src) {
        int i;
        char j;
        StringBuffer tmp = new StringBuffer();
        tmp.ensureCapacity(src.length() * 6);
        for (i = 0; i < src.length(); i++) {
            j = src.charAt(i);
            if (Character.isDigit(j) || Character.isLowerCase(j) || Character.isUpperCase(j))//指定字符是否为数字||指定字符是否为小写字母||指定字符是否为大写字母
                tmp.append(j);
            else if (j < 256) {
                tmp.append("%");
                if (j < 16) tmp.append("0");
                tmp.append(Integer.toString(j, 16));//把转换成16进制表示
            } else {
                tmp.append("%u");
                tmp.append(Integer.toString(j, 16));
            }
        }
        return tmp.toString();
    }

    public static String stringReplace(String from, String to, String source) {
        if (source == null) {
            return null;
        }
        // String temp1, temp2;

        int i = -1;// shenyg�޸ļ���Ҫ�滻��λ�������0�������˵� �����޸ĵ�ǰ����
        i = source.indexOf(from);
        while (i != -1) {
            source = source.substring(0, i).concat(to).concat(
                    source.substring(i + from.length()));
            i = source.indexOf(from);
        }
        return (source);
    }

    public static String converToString(java.util.Date dt, String type) {
        String returnStr = null;
        if (dt == null) {
            return null;
        } else {
            // YYYY-MM-DD HH24:MI:SS
            type = stringReplace("YYYY", "yyyy", type);
            type = stringReplace("DD", "dd", type);
            type = stringReplace("SS", "ss", type);
            type = stringReplace("hh24", "HH", type);
            type = stringReplace("HH24", "HH", type);
            type = stringReplace("MI", "mm", type);
            type = stringReplace("mi", "mm", type);
        }
        if (type == null || type.trim().equals("")) {
            returnStr = DateFormat.getDateTimeInstance().format(dt);
        } else {
            SimpleDateFormat f = new SimpleDateFormat(type);
            returnStr = f.format(dt);
        }
        return returnStr;
    }

    /**
     * HTML代码的UnEscape处理方法
     */
    public static String unescapeb(String src) {
        StringBuffer tmp = new StringBuffer();
        tmp.ensureCapacity(src.length());//设置字符串容量
        int lastPos = 0, pos = 0;
        char ch;
        while (lastPos < src.length()) {
            pos = src.indexOf("%", lastPos);//查找第一次出现%的位置
            if (pos == lastPos) {
                if (src.charAt(pos + 1) == 'u') {//查找第一次出现%的位置+1是否为u
                    ch = (char) Integer.parseInt(src.substring(pos + 2, pos + 6), 16);
                    tmp.append(ch);
                    lastPos = pos + 6;
                } else {
                    ch = (char) Integer.parseInt(src.substring(pos + 1, pos + 3), 16);
                    tmp.append(ch);
                    lastPos = pos + 3;
                }
            } else {
                if (pos == -1) {
                    tmp.append(src.substring(lastPos));
                    lastPos = src.length();
                } else {
                    tmp.append(src.substring(lastPos, pos));
                    lastPos = pos;
                }
            }
        }
        return tmp.toString();
    }

    /**
     * 为以逗号分隔的字符串的每个单元加入引号,如:aa,bb-->'aa','bb'
     */
    public static String formatString(String src) {
        StringBuffer result = new StringBuffer();
        result.append("");
        if (src != null) {
            String[] tmp = src.split(",");
            result.append("'" + tmp[0] + "'");
            for (int i = 1; i < tmp.length; i++) {
                result.append(",'" + tmp[i] + "'");
            }
        }
        return result.toString();
    }

    public static String cutString(String text, int textMaxChar) {
        return cutstr(text, textMaxChar, " ...");
    }

    public static String cutstr(String text, int length, String dot) {
        int strBLen = strlen(text);
        if (strBLen <= length) {
            return text;
        }
        int temp = 0;
        StringBuffer sb = new StringBuffer(length);
        char[] ch = text.toCharArray();
        for (char c : ch) {
            sb.append(c);
            if (c > 256) {
                temp += 2;
            } else {
                temp += 1;
            }
            if (temp >= length) {
                if (dot != null) {
                    sb.append(dot);
                }
                break;
            }
        }
        return sb.toString();
    }

    public static int strlen(String text) {
        return strlen(text, "UTF-8");
    }

    public static int strlen(String text, String charsetName) {
        if (text == null || text.length() == 0) {
            return 0;
        }
        int length = 0;
        try {
            length = text.getBytes(charsetName).length;
        } catch (UnsupportedEncodingException e) {
        	log.error("error",e);
        }
        return length;
    }

    /**
     * 按yyyy-MM-dd格式格式化日期
     */
    public static String formatDate(Date date) {
        if (date == null) {
            return "";
        } else {
            return df.format(date);
        }
    }

    /**
     * 按yyyy-MM-dd HH:mm:ss格式格式化日期
     */
    public static String formatDatehms(Date date) {
        if (date == null) {
            return "";
        } else {
            return df_.format(date);
        }
    }

    /**
     * 将短时间格式字符串转换为时间 yyyy-MM-dd
     *
     * @param strDate
     * @return
     */
    public static Date strToDatehms(String strDate) {
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = df_.parse(strDate, pos);

        return strtodate;
    }


    /**
     * 得到应用服务器当前日期，只有年月日，没有时分秒
     *
     * @return java.util.Date
     */
    public static java.sql.Date getDate() {
        Calendar oneCalendar = Calendar.getInstance();
        return getDate(oneCalendar.get(Calendar.YEAR), oneCalendar
                .get(Calendar.MONTH) + 1, oneCalendar.get(Calendar.DATE));
    }

    /**
     * 根据所给年、月、日，得到日期(java.util.Date类型)，注意：只有年月日，没有时分秒。
     * 年、月、日不合法会抛IllegalArgumentException
     *
     * @param yyyy 4位年
     * @param MM   月
     * @param dd   日
     * @return 日期
     */
    public static java.sql.Date getDate(int yyyy, int MM, int dd) {
        return getDate(yyyy, MM, dd, 0, 0, 0);
    }

    /**
     * 根据所给年、月、日、时、分、秒，得到日期(java.util.Date类型)。 年、月、日不合法会抛IllegalArgumentException
     *
     * @param yyyy 4位年
     * @param MM   月
     * @param dd   日
     * @param HH   时
     * @param mm   分
     * @param ss   秒
     * @return
     */
    public static java.sql.Date getDate(int yyyy, int MM, int dd, int HH,
                                        int mm, int ss) {
        if (!verityDate(yyyy, MM, dd))
            throw new IllegalArgumentException("不是有效的时间");
        Calendar oneCalendar = Calendar.getInstance();
        oneCalendar.clear();
        oneCalendar.set(yyyy, MM - 1, dd, HH, mm, ss);
        return new java.sql.Date(oneCalendar.getTime().getTime());
    }

    /**
     * 获取年、月、日、时、分、秒格式时间
     *
     * @return
     */
    public static Timestamp getTimestamp() {
        Date date = new Date();
        Timestamp nousedate = new Timestamp(date.getTime());
        return nousedate;

    }

    /**
     * 根据所给年、月、日，检验是否为合法日期。
     *
     * @param yyyy 4位年
     * @param MM   月
     * @param dd   日
     * @return
     */
    public static boolean verityDate(int yyyy, int MM, int dd) {
        boolean flag = false;

        if (MM >= 1 && MM <= 12 && dd >= 1 && dd <= 31) {
            if (MM == 4 || MM == 6 || MM == 9 || MM == 11) {
                if (dd <= 30)
                    flag = true;
            } else if (MM == 2) {
                if (yyyy % 100 != 0 && yyyy % 4 == 0 || yyyy % 400 == 0) {
                    if (dd <= 29)
                        flag = true;
                } else if (dd <= 28)
                    flag = true;

            } else
                flag = true;

        }
        return flag;
    }

    /**
     * 创建文件夹
     *
     * @param destDirName
     * @return
     * @author dingyulei
     */
    public static boolean createDir(String destDirName) {
        File dir = new File(destDirName);
        if (dir.exists()) {
            return false;
        }
        if (!destDirName.endsWith(File.separator))
            destDirName = destDirName + File.separator;
        // 创建单个目录
        return dir.mkdirs();
    }

    /**
     * 保存文件到硬盘
     *
     * @param filename
     * @param file
     * @return
     */
    public static boolean saveFile(String filename, File file) {
        FileOutputStream fos;
        try {
            fos = new FileOutputStream(filename);

            FileInputStream fis = new FileInputStream(file);
            byte[] buf = new byte[1024];
            int len = 0;
            while ((len = fis.read(buf)) > 0) {
                fos.write(buf, 0, len);
            }
            if (fis != null) fis.close();
            if (fos != null) fos.close();
            return true;
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
        	log.error("error",e);
            return false;
        } catch (IOException e) {
            // TODO Auto-generated catch block
        	log.error("error",e);
            return false;
        }
    }

    /**
     * 文件删除
     *
     * @param file
     */
    public static boolean deleteFile(File file) {
        if (file.exists()) {                    //判断文件是否存在
            if (file.isFile()) {                    //判断是否是文件
                file.delete();
                return true;//delete()方法 你应该知道 是删除的意思;
            } else if (file.isDirectory()) {              //否则如果它是一个目录
                File files[] = file.listFiles();               //声明目录下所有的文件 files[];
                for (int i = 0; i < files.length; i++) {            //遍历目录下所有的文件
                    deleteFile(files[i]);             //把每个文件 用这个方法进行迭代
                }
            }
            file.delete();
        } else {
            System.out.println("所删除的文件不存在！" + '\n');
            return false;
        }
        return true;
    }

    /**
     * 去除html标签的java正则表达方法
     *
     * @param html
     * @return
     */
    public static String replaceHtml(String html) {
        String regEx = "<.+?>"; //表示标签
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(html);
        String s = m.replaceAll("");
        return s;
    }

    /**
     * ip获取
     *
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    public static void main(String[] args) {
        System.out.println(escape(""));

    }

    /**
     * 是否有效的日期
     *
     * @param dateStr
     * @param pattern
     * @return
     */
    public static boolean isValidDate(String dateStr, String pattern) {
        java.text.SimpleDateFormat df = new java.text.SimpleDateFormat(pattern);
        try {
            df.setLenient(false);
            df.parse(dateStr);
            return true;
        } catch (ParseException e) {
        	log.error("error",e);
            return false;

        }
    }

    /**
     * 正则表达式匹配
     *
     * @param var
     * @param pattern
     * @return
     * @author dingyulei
     */
    public static boolean regularString(String var, String pattern) {
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(var);
        return m.find();
    }

    public static List<String> regularpp(String var, String pattern) {
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(var);
        List<String> list = new ArrayList<String>();
        while (m.find()) {
            list.add(m.group(1));
        }
        return list;
    }

    public static boolean in_array(Object source, Object ext, boolean strict) {
        if (source == null || ext == null) {
            return false;
        }
        if (source instanceof Collection) {
            for (Object s : (Collection) source) {
                if (s.toString().equals(ext.toString())) {
                    if (strict) {
                        if ((s.getClass().getName().equals(ext.getClass().getName()))) {
                            return true;
                        }
                    } else {
                        return true;
                    }
                }
            }
        } else {
            for (Object s : (Object[]) source) {
                if (s.toString().equals(ext.toString())) {
                    if (strict) {
                        if ((s.getClass().getName().equals(ext.getClass().getName()))) {
                            return true;
                        }
                    } else {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 从json HASH表达式中获取一个map，改map支持嵌套功能
     *
     * @param jsonString
     * @return
     */
    public static Map mapToJson(String jsonString) {
        Map valueMap = new HashMap();
        if (jsonString == null) {
            return valueMap;
        }
        JSONObject jsonObject = JSONObject.fromObject(jsonString);
        Iterator keyIter = jsonObject.keys();
        String key;
        Object value;


        while (keyIter.hasNext()) {
            key = (String) keyIter.next();
            value = jsonObject.get(key);
            valueMap.put(key, value);
        }

        return valueMap;
    }

    /**
     * map形式的数据集转json
     *
     * @param mapdata
     * @return
     * @author dingyulei
     */
    public static String spanJson(List<?> mapdata) {
        StringBuffer sb = new StringBuffer();
        if (mapdata != null) {
            JSONArray json = JSONArray.fromObject(mapdata);
            sb.append(json.toString());
        } else {
            sb.append("[]");
        }
        return sb.toString();
    }


    /**
     * 从request中获得参数Map，并返回可读的Map
     *
     * @param request
     * @return
     */
    @SuppressWarnings("unchecked")
    public static Map getParameterMap(HttpServletRequest request) {
        // 参数Map
        Map properties = request.getParameterMap();
        // 返回值Map
        Map returnMap = new TreeMap();
        Iterator entries = properties.entrySet().iterator();
        Map.Entry entry;
        String name = "";
        String value = "";
        while (entries.hasNext()) {
            entry = (Map.Entry) entries.next();
            name = (String) entry.getKey();
            Object valueObj = entry.getValue();
            if (null == valueObj) {
                value = "";
                returnMap.put(name, value);
            } else if (valueObj instanceof String[]) {
                String[] values = (String[]) valueObj;

                if (values.length > 1) {
                    returnMap.put(name, valueObj);
                } else {
                    for (int i = 0; i < values.length; i++) {
                        value = values[i] + ",";
                    }
                    value = value.substring(0, value.length() - 1);
                    returnMap.put(name, value);
                }
            } else {
                value = valueObj.toString();
                returnMap.put(name, value);
            }

        }
        return returnMap;
    }

    /**
     * 按长度截取字符串
     *
     * @param s
     * @param i
     * @return
     * @author dingyulei
     */
    public static String subStrLen(String s, int i) {
        int temptitlelen = i;
        if (s.length() > temptitlelen) {//标题字符长度超长
            s = cutString(s, temptitlelen * 2);
        }
        return s;

    }

    public static boolean empty(Object obj) {
        if (obj == null) {
            return true;
        } else if (obj instanceof String && (obj.equals(""))) {
            return true;
        } else if (obj instanceof Number && ((Number) obj).doubleValue() == 0) {
            return true;
        } else if (obj instanceof Boolean && !((Boolean) obj)) {
            return true;
        } else if (obj instanceof Collection && ((Collection) obj).isEmpty()) {
            return true;
        } else if (obj instanceof Map && ((Map) obj).isEmpty()) {
            return true;
        } else if (obj instanceof Object[] && ((Object[]) obj).length == 0) {
            return true;
        }
        return false;
    }

    public static String getFirstImg(String content) {
        String regex = "<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(content);
        String result = "";
        if (m.find()) {
            result = m.group(1);
        }
        return result;
    }

    public static String getStringRand(int num) {
        Random random = new Random();
        String sRand = "";
        for (int i = 0; i < num; i++) {
            String rand = String.valueOf(random.nextInt(10));
            sRand += rand;

        }
        return sRand;
    }

    // 在src中查找符合regEx指定的模式或子串，并替换为rep指定的子串
    // 返回替换后的结果
    public static String invokeRegx(String src, String regEx, String rep) {
        Pattern pat = Pattern.compile(regEx);
        Matcher matcher = pat.matcher(src);
        if (matcher.find()) {
            return matcher.replaceAll(rep);
        } else {
            return src;
        }

    }

    /**
     * 把字符串的后n位用“*”号代替
     *
     * @param str 要代替的字符串
     * @param n   代替的位数
     * @return
     */
    public static String replaceSubString(String str) {

        try {
            if (str == null || str.equals("")) {
                return "匿名";
            }
            String subs = str.substring(0, 3);
            String sube = str.substring(7, 11);
            return subs + "****" + sube;
        } catch (Exception e) {
            // TODO Auto-generated catch block
        	log.error("error",e);
            return str;
        }

    }


    public static BigDecimal getBigDecimal(Object value) {
        BigDecimal ret = null;
        if (value != null) {
            if (value instanceof BigDecimal) {
                ret = (BigDecimal) value;
            } else if (value instanceof String) {
                ret = new BigDecimal((String) value);
            } else if (value instanceof BigInteger) {
                ret = new BigDecimal((BigInteger) value);
            } else if (value instanceof Number) {
                ret = new BigDecimal(((Number) value).doubleValue());
            } else {
                throw new ClassCastException("Not possible to coerce [" + value + "] from class " + value.getClass() + " into a BigDecimal.");
            }
        }
        return ret;
    }

    public static String zfmailhead(String fnames, String addtime, String snames, String thema) {
        StringBuffer sb = new StringBuffer();
        sb.append("<p><br></p><p><br></p><div style=\"font-size:12px;font-family:Arial Narrow;\">------------------&nbsp;原始邮件&nbsp;------------------</div>");
        sb.append("<div style=\"font-size:12px;background:#efefef;\">");
        sb.append("<div><b>发件人:</b>" + fnames + "</div>");
        sb.append("<div><b>发送时间:</b>" + addtime + "</div>");
        sb.append("<div><b>收件人:</b>" + snames + "</div>");
        sb.append("<div><b>主题:</b>" + thema + "</div>");
        sb.append("</div>");
        return sb.toString();
    }

}
